package com.lanren.familybookapp.ui.me.view;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hjq.toast.ToastUtils;
import com.lanren.common.helper.glidehelp.GlideHelper;
import com.lanren.common.utils.DateUtils;
import com.lanren.common.utils.FileUtils;
import com.lanren.common.utils.LogUtils;
import com.lanren.common.utils.StringUtils;
import com.lanren.common.utils.Utils;
import com.lanren.common.utils.event.C;
import com.lanren.common.widget.SettingBar;
import com.lanren.common.widget.TitleBarView;
import com.lanren.common.widget.image.RoundedImageView;
import com.lanren.common.widget.pickerview.TimePickerDialog;
import com.lanren.common.widget.pickerview.data.Type;
import com.lanren.common.widget.pickerview.listener.OnDateSetListener;
import com.lanren.common.widget.statusbar.ImmersionBar;
import com.lanren.easyeventbus.Event;
import com.lanren.easyeventbus.EventBusUtil;
import com.lanren.easyhttp.body.UIProgressResponseCallBack;
import com.lanren.easyhttp.subsciber.IProgressDialog;
import com.lanren.familybookapp.R;
import com.lanren.familybookapp.app.AppUserHelper;
import com.lanren.familybookapp.app.MyApplication;
import com.lanren.familybookapp.base.BaseUiActivity;
import com.lanren.familybookapp.helper.DialogHelper;
import com.lanren.familybookapp.ui.me.interfaces.IOneselfModel;
import com.lanren.familybookapp.ui.me.presenter.OneselfPresenter;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @ClassName OneselfActivity
 * @Description TODO 个人资料
 * @Author chongheng.wang
 * @Date 2019/10/11 13:53
 * @Version 1.0
 */
public class OneselfActivity extends BaseUiActivity<OneselfPresenter> implements IOneselfModel.IOneselfView {

    @BindView(R.id.title_view)
    TitleBarView titleView;
    @BindView(R.id.user_avatar)
    RoundedImageView userAvatar;
    @BindView(R.id.changer_avatar)
    TextView changerAvatar;
    @BindView(R.id.user_name)
    SettingBar userName;
    @BindView(R.id.user_sex)
    SettingBar userSex;
    @BindView(R.id.user_age)
    SettingBar userAge;
    @BindView(R.id.user_email)
    SettingBar userEmail;
    @BindView(R.id.user_name_id)
    SettingBar userNameId;

    private TimePickerDialog mDialogYearMonth;

    private File outputImage;
    private Uri imageUri;
    private File CropPhoto;

    private int PHOTO_REQUEST_CAREMA = 0;//相机
    private int PHOTO_REQUEST_GALLERY = 1;//相册
    private int PHOTO_REQUEST_CUT = 3;//剪切

    private ProgressDialog dialog;
    private IProgressDialog mProgressDialog = new IProgressDialog() {
        @Override
        public Dialog getDialog() {
            if (dialog == null) {
                dialog = new ProgressDialog(OneselfActivity.this);
                dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置进度条的形式为圆形转动的进度条
                dialog.setMessage("正在上传...");
                // 设置提示的title的图标，默认是没有的，如果没有设置title的话只设置Icon是不会显示图标的
                dialog.setTitle("文件上传");
                dialog.setMax(100);
            }
            return dialog;
        }
    };


    @Override
    public OneselfPresenter createPresenter() {
        return new OneselfPresenter();
    }

    @Override
    protected void setStatusBar() {
        mImmersionBar = ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_oneself;
    }

    @Override
    public void doCreate(Bundle savedInstanceState) {
        initView();
        initData();
        initEvent();
    }

    public void initView() {
        mDialogYearMonth = new TimePickerDialog.Builder()
                .setThemeColor(getResources().getColor(R.color.green10))
                .setTitleStringId("请选择出身年份")
                .setMinMillseconds(DateUtils.rollYear(new Date(), -100).getTime())
                .setMaxMillseconds(DateUtils.rollDay(new Date(), 7).getTime())
                .setCurrentMillseconds(DateUtils.getNowTime())
                .setType(Type.YEAR)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        int oldTime = Integer.valueOf(DateUtils.longToFormat(millseconds, "yyyy"));
                        int newTime = Integer.valueOf(DateUtils.longToFormat(DateUtils.getNowTime(), "yyyy"));
                        mPresenter.updateUserInfo(null, null, (newTime - oldTime) + "");
                    }
                })
                .setCyclic(false)
                .build();
    }

    @SuppressLint("SetTextI18n")
    public void initData() {
        setData();
    }

    public void initEvent() {
        titleView.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected boolean registEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case C.EventCode.REFRESH_USER_INFO:
                setData();
                break;
        }
    }

    private void setData() {
        GlideHelper.setImageResourceMemoryCache(this, userAvatar, AppUserHelper.getInstance().getUser().getUserAvatar(), R.mipmap
                .icon_app, true, DiskCacheStrategy.NONE);
        userNameId.setRightText(StringUtils.replaceNullByPstr(AppUserHelper.getInstance().getUser().getUserId(), "--"));
        userName.setRightText(StringUtils.replaceNullByPstr(AppUserHelper.getInstance().getUser().getUserName(), "还木有昵称"));
        if (AppUserHelper.getInstance().getUser().getUserSex() == null) {
            userSex.setRightText("请设置");
        } else {
            if (AppUserHelper.getInstance().getUser().getUserSex() == 1) {
                userSex.setRightText("男");
            } else {
                userSex.setRightText("女");
            }
        }
        if (AppUserHelper.getInstance().getUser().getUserAge() == null) {
            userAge.setRightText("请设置");
        } else {
            userAge.setRightText(AppUserHelper.getInstance().getUser().getUserAge() + "");
        }
        userEmail.setRightText(StringUtils.replaceNullByPstr(AppUserHelper.getInstance().getUser().getUserEmail(), "绑定邮箱"));

    }

    @Override
    public void showError(int code, String msg) {
        super.showError(code, msg);
    }

    @Override
    public void onSuccess() {
        EventBusUtil.sendEvent(new Event(C.EventCode.REFRESH_USER_INFO));
    }

    @OnClick({R.id.changer_avatar, R.id.user_name, R.id.user_sex, R.id.user_age, R.id.user_email})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.changer_avatar:
                if (Utils.isFastClick(view)) {
                    List<String> list = new ArrayList<>();
                    list.add("相机");
                    list.add("手机相册");

                    DialogHelper.getInstance().showMenuDialog(this, list, false, new DialogHelper.OnSelectedListener() {
                        @Override
                        public void onSelected(int position, String text) {
                            if (position == 0) {
                                getCameraFile();
                            } else {
                                getGalleryFile();
                            }
                        }
                    });
                }
                break;
            case R.id.user_name:
                if (Utils.isFastClick(view)) {
                    DialogHelper.getInstance().showInputDialog(this, "昵称", 10, new DialogHelper.OnClickListener() {
                        @Override
                        public void onClicks(String msg) {
                            mPresenter.updateUserInfo(msg, null, null);
                        }

                    });
                }
                break;
            case R.id.user_sex:
                if (Utils.isFastClick(view)) {
                    List<String> sexList = new ArrayList<>();
                    sexList.add("男");
                    sexList.add("女");

                    DialogHelper.getInstance().showMenuDialog(this, sexList, false, new DialogHelper.OnSelectedListener() {
                        @Override
                        public void onSelected(int position, String text) {
                            if (position == 0) {
                                mPresenter.updateUserInfo(null, "1", null);
                            } else {
                                mPresenter.updateUserInfo(null, "2", null);
                            }
                        }
                    });
                }
                break;
            case R.id.user_age:
                if (Utils.isFastClick(view)) {
                    mDialogYearMonth.show(this);
                }
                break;
            case R.id.user_email:
                if (Utils.isFastClick(view)) {
                    startActivity(BookEmailActivity.class);
                }
                break;
        }
    }


    final UIProgressResponseCallBack listener = new UIProgressResponseCallBack() {
        @Override
        public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
            int progress = (int) (bytesRead * 100 / contentLength);
            LogUtils.d(progress + "% ");
            dialog.setProgress(progress);
            dialog.setMessage(progress + "%");
            if (done) {//完成
                dialog.setMessage("上传完整");
                GlideHelper.setImageResourceMemoryCache(OneselfActivity.this, userAvatar, CropPhoto.getAbsolutePath(), R.mipmap
                        .icon_app, true, DiskCacheStrategy.NONE);
            }
        }
    };

    public void getLocalFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, new ActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, @Nullable Intent data) {

                Uri uri = data.getData();
                LogUtils.d("File uri" + uri);
                if (uri != null) {
                    String path = FileUtils.getPath2uri(OneselfActivity.this, uri);
                    if (path != null) {
                        File file = new File(path);
                        if (file.exists()) {
                            String mPath = file.toString();
                            mPresenter.updateFile(mPath, mProgressDialog, listener);
                            LogUtils.d("File path" + mPath);
                        }
                    }
                }
            }
        });
    }

    public void getGalleryFile() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }


    private void getCameraFile() {
        outputImage = new File(Environment.getExternalStorageDirectory() + "/Family/file", "output_image.png");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.getParentFile().mkdirs();
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 设置action
        if (Build.VERSION.SDK_INT >= 24) {
//          第一个参数Context，第二个参数随便写个字符串，第三个参数就是我们刚刚创建的File对象
            imageUri = FileProvider.getUriForFile(OneselfActivity.this, MyApplication.getApplication().getPackageName() + ".lanren", outputImage);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            imageUri = Uri.fromFile(outputImage);
        }
        //启动相机程序
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//指定图片的输出地址
        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);

    }

    /*
     * 剪切图片
     */
    private void crop(Uri uri) {
        CropPhoto = new File(Environment.getExternalStorageDirectory() + "/Family/file", "crop_image.png");
        try {
            if (CropPhoto.exists()) {
                CropPhoto.delete();
            }
            CropPhoto.getParentFile().mkdirs();
            CropPhoto.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri cropImageUri = Uri.fromFile(CropPhoto);
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intent.putExtra("crop", "true");
//        // 裁剪框的比例，1：1
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        // 裁剪后输出图片的尺寸大小
//        intent.putExtra("outputX", 250);
//        intent.putExtra("outputY", 250);
        // 裁剪框的比例，4：3
        intent.putExtra("aspectX", 4);
        intent.putExtra("aspectY", 3);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 800);
        intent.putExtra("outputY", 600);

        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                crop(data.getData());//裁剪图片
            }
        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            if (resultCode == RESULT_OK) {
                crop(imageUri);//裁剪图片
            } else {
                ToastUtils.show("未找到存储卡，无法存储照片！");
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            if (data != null) {
                mPresenter.updateFile(CropPhoto.getAbsolutePath(), mProgressDialog, listener);
                try {
                    // 将临时文件删除
                    outputImage.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDialogYearMonth != null) {
            mDialogYearMonth.clearDialog();
            mDialogYearMonth = null;
        }
    }
}
